<template>
  <div>
    <a-card :bordered="false">
      <f-search-form :more="false" @searchHandler="searchHandler"  :tableObj="$refs.table">
        <f-search-form-item label="服务WBS" name="serviceWbsCode"/>
        <f-search-form-item label="服务代码" name="serviceCode"/>
        <f-search-form-item label="项目（名称）" name="materiaSpecs"/>
        <f-search-form-item label="层级号" name="levelNo"/>
        <f-search-form-item label="科目名称" name="subjectName" slot="advanced"/>
        <f-search-form-item label="区域" name="materialArea" slot="advanced"/>
        <f-search-form-item label="系统" name="materialUse" slot="advanced"/>
      </f-search-form>
      <f-table ref="table" rowKey="materialPackage100Id" :scroll="{x:columns.length*150,y:columns.length*35}"
               :columns="columns"
               :exportBtn="false"
               :multiple="false" :operator="operator" :params="queryParam" :api="api.bmp"
               handler="materialPackagePageListHandler">
        <span slot="applayStatus" slot-scope="text, record">
            <a-tag v-if="record.applayStatus ===''">--</a-tag>
            <a-tag v-if="record.applayStatus !=='' && record.applayStatus == 0">待审核</a-tag>
            <a-tag v-if="record.applayStatus == 1" color="pink">审核中</a-tag>
            <a-tag v-if="record.applayStatus == 2" color="green">审批通过</a-tag>
        </span>
        <span slot="action" slot-scope="text, record,index">
          <template>
            <a @click="handleAdd(record)">添加</a>
          </template>
        </span>
      </f-table>
      <a-divider orientation="left">添加</a-divider>
      <a-table ref="copyTable" bordered :scroll="{x:columns2.length*150,y:columns.length*35}" :data-source="dataSource"
               :columns="columns2" rowKey="key">
        <span slot="applayStatus" slot-scope="text, record">
          <a-tag v-if="record.applayStatus ===''">--</a-tag>
          <a-tag v-if="record.applayStatus !=='' && record.applayStatus == 0">待审核</a-tag>
          <a-tag v-if="record.applayStatus == 1" color="pink">审核中</a-tag>
          <a-tag v-if="record.applayStatus == 2" color="green">审批通过</a-tag>
        </span>
        <!-- 编辑 -->
        <template v-for="col in editSlots" :slot="col" slot-scope="text, record, index">
          <div :key="col">
            <a-input
              v-if="record.editable"
              style="margin: -5px 0"
              :value="text"
              @change="e => handleChange(e.target.value, record.key, col)"
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template slot="action" slot-scope="text, record, index">
          <a-popconfirm
            v-if="dataSource.length"
            title="Sure to delete?"
            @confirm="() => onDelete(record.key)"
          >
            <a href="javascript:;">删除</a>
          </a-popconfirm>
          <a-divider type="vertical"/>
          <div class="editable-row-operations">
              <span v-if="record.editable">
                <a @click="() => save(record.key)">保存</a>
                <a-popconfirm title="Sure to cancel?" @confirm="() => cancel(record.key)">
                  <a>取消</a>
                </a-popconfirm>
              </span>
            <span v-else>
                <a :disabled="editingKeys.includes(record.key)" @click="() => edit(record.key)">编辑</a>
              </span>
          </div>
        </template>
      </a-table>
      <material-package100-drawer ref="materialPackage100Drawer"
                                  :detailsParams="detailsParams"></material-package100-drawer>
      <upload-modal ref="uploadModal" :action="api.bmp.import100AddData" :otherParams="otherParams"
                    @change="uploadEnd"></upload-modal>
    </a-card>
  </div>
</template>
<script>
  import api from './js/api'
  import materialPackage100Drawer from './material_package100_drawer'

  export default {
    name: 'TableList',
    props: {
      detailsParams: {}
    },
    components: {
      materialPackage100Drawer
    },
    data() {
      let me = this
      //操作按钮
      let operator = []
      operator.push({
        name: '添加',
        icon: '',
        that: this,
        handler: function(table, that) {
          that.http.get(that, {
            url: that.api.project.projectStatus,
            data: {
              projectId: that.queryParam.projectId
            },
            success: function(me, data) {
              let projectStatus = data
              if (projectStatus == 1) {
                me.$message.error('项目已锁定不支持操作')
              } else {
                that.$refs.materialPackage100Drawer.showDrawer(1)
              }
            }
          })
        }
      })
      operator.push({
        name: '提交oa合并审批',
        icon: '',
        that: this,
        handler: function(table, that) {
          that.http.get(that, {
            url: that.api.project.projectStatus,
            data: {
              projectId: that.queryParam.projectId
            },
            success: function(me, data) {
              let projectStatus = data
              if (projectStatus == 1) {
                me.$message.error('项目已锁定不支持操作')
              } else {
                that.merge100()
              }
            }
          })
        }
      })
      operator.push({
        name: '提交',
        icon: '',
        that: this,
        handler: function(table, that) {
          that.http.get(that, {
            url: that.api.project.projectStatus,
            data: {
              projectId: that.queryParam.projectId
            },
            success: function(me, data) {
              let projectStatus = data
              if (projectStatus == 1) {
                me.$message.error('项目已锁定不支持操作')
              } else {
                that.copyAndUpdate(that.cacheData)
              }
            }
          })
        }
      })
      operator.push({
        name: '下载模板',
        icon: '',
        that: this,
        handler: function(table, that) {
          let columns = table.getExportColumns(that.columns)
          columns.push({ name: '是否新增', isStatistics: '0', key: 'isAdd' })
          columns.push({ name: '数据种类', key: 'dataType' })
          that.detailsParams['columns'] = JSON.stringify(columns)
          that.download100Template(table)
        }
      })
      operator.push({
        name: '导入数据',
        icon: '',
        that: this,
        handler: function(table, that) {
          console.info("otherParams",that.otherParams)
          that.http.get(that, {
            url: that.api.project.projectStatus,
            data: {
              projectId: that.queryParam.projectId
            },
            success: function(me, data) {
              let projectStatus = data
              if (projectStatus == 1) {
                me.$message.error('项目已锁定不支持操作')
              } else {
                that.$refs.uploadModal.open()
              }
            }
          })
        }
      })
      return {
        api: Object.assign(api, this.api),
        //列表初始化查询参数
        queryParam: {},
        // 表头
        columns: [
          {
            title: '序号',
            width: 80,
            align: 'center',
            customRender: (text, record, index) => index + 1
          },
          {
            title: '分包Id',
            width: 180,
            align: 'center',
            dataIndex: 'materialPackage100Id'
          },
          {
            title: '项目代码',
            width: 150,
            align: 'center',
            dataIndex: 'projectCode'
          },
          {
            title: '项目名称',
            width: 150,
            align: 'center',
            dataIndex: 'projectName'
          },
          {
            title: '服务代码',
            width: 150,
            align: 'center',
            dataIndex: 'serviceCode'
          },
          {
            title: '服务WBS代码',
            width: 150,
            align: 'center',
            dataIndex: 'serviceWbsCode'
          },
          {
            title: '项目（名称）',
            width: 150,
            align: 'center',
            dataIndex: 'materiaSpecs'
          },
          {
            title: '科目名称',
            width: 150,
            align: 'center',
            dataIndex: 'subjectName'
          },
          {
            title: '层级号',
            width: 150,
            align: 'center',
            dataIndex: 'levelNo'
          },
          {
            title: '分承包发包项目描述',
            width: 200,
            align: 'center',
            dataIndex: 'packageDesc'
          },
          {
            title: '区域',
            width: 150,
            align: 'center',
            dataIndex: 'materialArea'
          },
          {
            title: '系统',
            width: 150,
            align: 'center',
            dataIndex: 'materialUse'
          },
          {
            title: '计量单位',
            width: 150,
            align: 'center',
            dataIndex: 'measurementUnit'
          },
          {
            title: '标前工程量',
            width: 150,
            align: 'center',
            dataIndex: 'beforeMarkQuantity'
          },
          {
            title: '100预算成本工程量',
            width: 200,
            align: 'center',
            dataIndex: 'costQuantity100'
          }
        ],
        operator: operator,
        columns2: [
          {
            title: '序号',
            width: 80,
            align: 'center',
            customRender: (text, record, index) => index + 1
          },
          {
            title: '分包Id',
            width: 180,
            align: 'center',
            dataIndex: 'materialPackage100Id'
          },
          {
            title: '项目代码',
            width: 150,
            align: 'center',
            dataIndex: 'projectCode'
          },
          {
            title: '项目名称',
            width: 150,
            align: 'center',
            dataIndex: 'projectName'
          },
          {
            title: '服务代码',
            width: 150,
            align: 'center',
            dataIndex: 'serviceCode'
          },
          {
            title: '服务WBS代码',
            width: 150,
            align: 'center',
            dataIndex: 'serviceWbsCode'
          },
          {
            title: '项目（名称）',
            width: 150,
            align: 'center',
            dataIndex: 'materiaSpecs'
          },
          {
            title: '科目名称',
            width: 150,
            align: 'center',
            dataIndex: 'subjectName'
          },
          {
            title: '层级号',
            width: 150,
            align: 'center',
            dataIndex: 'levelNo'
          },
          {
            title: '分承包发包项目描述',
            width: 200,
            align: 'center',
            dataIndex: 'packageDesc'
          },
          {
            title: '区域',
            width: 150,
            align: 'center',
            dataIndex: 'materialArea'
          },
          {
            title: '系统',
            width: 150,
            align: 'center',
            dataIndex: 'materialUse'
          },
          {
            title: '计量单位',
            width: 150,
            align: 'center',
            dataIndex: 'measurementUnit'
          },
          {
            title: '标前工程量',
            width: 150,
            align: 'center',
            dataIndex: 'beforeMarkQuantity'
          },
          {
            title: '100预算成本工程量',
            width: 200,
            align: 'center',
            dataIndex: 'costQuantity100',
            scopedSlots: { customRender: 'costQuantity100' }
          }
        ],
        dataSource: [],
        editSlots: ['costQuantity100'],
        editingKeys: [],
        count: 1,
        cacheData: [],
        otherParams: {},
        supplierNumTagList: []
      }
    },
    created() {
      let params = { ...this.detailsParams }
      this.queryParam = params
      params.type = 1
      this.otherParams = params
      this.getBusProjectSupplierList()
    },
    methods: {
      getBusProjectSupplierList() {
        this.http.get(this, {
          url: this.api.bmp.getBusProjectSupplierList,
          data: this.detailsParams,
          success(me, data) {
            console.log(data)
            for (let i in data) {
              let info = data[i]
              me.supplierNumTagList.push(info.index)
              me.columns.push({
                title: info.supplierName + '合同量',
                width: 250,
                align: 'center',
                dataIndex: 'supplierNum' + info.index
              })
              me.columns2.push({
                title: info.supplierName + '合同量',
                width: 250,
                align: 'center',
                dataIndex: 'supplierNum' + info.index,
                scopedSlots: { customRender: 'supplierNum' + info.index }
              })
              me.editSlots.push('supplierNum' + info.index)
            }
            me.columns.push({
              title: 'oa审批状态',
              width: 150,
              align: 'center',
              dataIndex: 'applayStatus',
              scopedSlots: { customRender: 'applayStatus' }
            })

            me.columns.push({
              title: '操作',
              width: 150,
              align: 'center',
              scopedSlots: { customRender: 'action' },
              fixed: 'right'
            })

            me.columns2.push({
              title: 'oa审批状态',
              width: 150,
              align: 'center',
              dataIndex: 'applayStatus',
              scopedSlots: { customRender: 'applayStatus' }
            })
            me.columns2.push({
              title: '操作',
              width: 150,
              align: 'center',
              scopedSlots: { customRender: 'action' },
              fixed: 'right'
            })
          }
        })
      },
      onCellChange(key, dataIndex, value) {
        const dataSource = [...this.dataSource]
        const target = dataSource.find(item => item.key === key)
        if (target) {
          target[dataIndex] = value
          this.dataSource = dataSource
        }
      },
      onDelete(key) {
        const dataSource = [...this.dataSource]
        this.dataSource = dataSource.filter(item => item.key !== key)
      },
      handleAdd(record) {
        this.http.get(this, {
          url: this.api.project.projectStatus,
          data: {
            projectId: record.projectId
          },
          success: function(me, data) {
            let projectStatus = data
            if (projectStatus == 1) {
              me.$message.error('项目已锁定不支持操作')
            } else {
              let applayStatus = record.applayStatus
              if (applayStatus ==1) {
                me.$message.error('该项已被锁定')
              } else {
                record['isSave'] = false
                //复制一条
                let newData = JSON.stringify(record)
                newData = JSON.parse(newData)
                //设置新添加的变更数据 审批状态为0 --
                newData['applayStatus'] = ''
                newData['key'] = me.count
                me.dataSource = [...me.dataSource, newData]
                me.count += 1
                me.cacheData = me.dataSource.map(item => ({ ...item }))
              }
            }
          }
        })
      },
      handleChange(value, key, column) {
        const newData = [...this.dataSource]
        const target = newData.filter(item => key === item.key)[0]
        if (target) {
          target[column] = value
          this.dataSource = newData
        }
      },
      edit(key) {
        console.log(key)
        const newData = [...this.dataSource]
        const target = newData.filter(item => key === item.key)[0]
        console.log(target)
        this.editingKeys.push(key)
        if (target) {
          target.editable = true
          this.dataSource = newData
        }
      },
      save(key) {
        const newData = [...this.dataSource]
        const newCacheData = [...this.cacheData]
        const target = newData.filter(item => key === item.key)[0]
        let costQuantity100 = target['costQuantity100']
        let allSupplierNum = 0
        for (let i in this.supplierNumTagList) {
          let tag = this.supplierNumTagList[i]
          allSupplierNum = allSupplierNum + parseFloat(target['supplierNum' + tag])
        }
        if (costQuantity100 < allSupplierNum) {
          this.$message.warn('包商总合同量必须小于等于工程量')
          return
        }
        const targetCache = newCacheData.filter(item => key === item.key)[0]
        if (target && targetCache) {
          target['isSave'] = true
          delete target.editable
          this.dataSource = newData
          Object.assign(targetCache, target)
          this.cacheData = newCacheData
        }
        this.editingKeys = []
      },
      cancel(key) {
        const newData = [...this.dataSource]
        const target = newData.filter(item => key === item.key)[0]
        this.editingKeys = []
        if (target) {
          Object.assign(target, this.cacheData.filter(item => key === item.key)[0])
          delete target.editable
          this.data = newData
        }
      },
      copyAndUpdate(cacheData) {
        let noSaveLength = cacheData.filter(item => item.isSave === false).length
        if (noSaveLength > 0) {
          this.$message.warn('提交之前先进行保存操作')
          return
        }
        let copyData = JSON.stringify(cacheData)
        let that = this
        console.log(copyData)
        that.http.post(that, {
          url: that.api.bmp.copyAndUpdate,
          data: {
            copyDataStr: copyData,
            projectId: this.detailsParams.projectId,
            type: 1
          },
          success(me, data) {
            that.cacheData = []
            that.dataSource = []
            that.$refs.table.refresh(false, that.queryParam)
            that.$bus.emit('refreshDetailsMaterialPackage100')
          }
        })
      },
      merge100() {
        let that = this
        that.http.post(that, {
          url: that.api.bmp.merge100,
          data: {
            projectId: that.detailsParams.projectId,
            packageNo: that.detailsParams.packageNo,
            majorCode: that.detailsParams.majorCode,
            type:1
          },
          success(me, data) {
            me.$message.success(data)
          }
        })
      },
      download100Template(table) {
        let that = this
        let queryParams = { ...table.searchParams }
        let detailsParams = { ...that.detailsParams }
        let params = Object.assign(detailsParams, queryParams)
        that.http.exportExcel(that, {
          url: that.api.bmp.export100Template,
          data: params
        })
      },
      uploadEnd(file, fileList, event) {
        this.$refs.uploadModal.close()
        let errMsg = ""
        if(fileList.response.code == "100") {
          errMsg = '导入成功'
          this.$message.success(errMsg)
        } else {
          errMsg = fileList.response.message
          this.$message.error(errMsg)
        }
        this.$refs.table.refresh(false, this.queryParam)
        this.$bus.emit('refreshDetailsMaterialPackage100')
      }
    }
  }
</script>
<style scoped>
  .editable-row-operations a {
    margin-right: 8px;
  }
</style>